import {Component, OnInit} from '@angular/core';
import {AlertController, Events, ModalController, NavController, ToastController} from '@ionic/angular';
import {ActivatedRoute} from '@angular/router';
import {HttpService} from '../../services/http.service';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {BasePage} from '../../common/basePage';
import {ConfigService} from '../../services/config.service';
import {AppConfig} from '../../common/app-config.enum';

@Component({
  selector: 'app-user-loan-bill-detail',
  templateUrl: './user-loan-bill-detail.page.html',
  styleUrls: ['./user-loan-bill-detail.page.scss'],
})
export class UserLoanBillDetailPage extends BasePage implements OnInit {

  data: any = {};
  totalPeriod: number;

  constructor(
    public configService: ConfigService,
    public navCtrl: NavController,
    public toastCtrl: ToastController,
    private alertCtrl: AlertController,
    private modalCtrl: ModalController,
    private events: Events,
    private routeInfo: ActivatedRoute,
    private service$: HttpService
  ) {
    super(navCtrl, toastCtrl);
  }

  ngOnInit() {
    this.getData();
  }

  private getData() {
    if (this.routeInfo.snapshot.params['bidId'] && this.routeInfo.snapshot.params['billIdSign']) {
      this.service$.doRequest(UrlAndOPT.auth_user_loan_bill_detail, {
        bidId: this.routeInfo.snapshot.params['bidId'],
        billIdSign: this.routeInfo.snapshot.params['billIdSign']
      })
        .subscribe(obj => {
          if (obj) {
            this.data = obj['billInfo'];
            this.totalPeriod = obj['totalPeriod'];
          }
        });
    }
  }

  async presentAlertConfirm() {
    const alert = await this.alertCtrl.create({
      header: '提示',
      message: '是否还款？',
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        }, {
          text: '确定',
          handler: async () => {
            await this.doRepay();
          }
        }
      ]
    });
    await alert.present();
  }

  async doRepay() {
    this.service$.doRequest(UrlAndOPT.auth_user_loan_bill_repay, {billIdSign: this.data['billIdSign']})
      .subscribe(obj => {
        if (obj) {
          this.events.publish(AppConfig.TOPIC_USER_FUNC);
          this.showToast('还款成功');
          this.doPop();
        }
      });
  }

}
